//
#include "zy_net.h"
#include <iostream>
#include <string>
#include <fstream>
#include <locale>
#include <cerrno>

using namespace std;

// (in_addr_t) 0x00000000
int start_ts(in_addr_t host_ip, int PORT, TsRequestHandler handler, IcrDb& icrDb) {
    
    // 设置UTF-8编码环境
    locale::global(locale("en_US.utf-8"));
    wcout.imbue(locale());

    int server_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    // const int PORT = 8080;
    static int id_counter = 0;

    // 创建TCP socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置socket选项
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("setsockopt failed");
        exit(EXIT_FAILURE);
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = host_ip; //INADDR_ANY;
    address.sin_port = htons(PORT);

    // 绑定地址和端口
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 开始监听
    if (listen(server_fd, 3) < 0) {
        perror("listen failed");
        exit(EXIT_FAILURE);
    }
    cout << "Server listening on port " << PORT << "..." << endl;

    // 处理客户端连接
    while (true) {
        if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
            perror("accept failed");
            continue;
        }

        // 接收客户端数据
        char buffer[1024] = {0};
        int bytes_received = read(new_socket, buffer, 1024);
        if (bytes_received <= 0) {
            close(new_socket);
            continue;
        }

        string request(buffer, bytes_received);
        // 去除换行符和空格
        request.erase(request.find_last_not_of("\r\n") + 1);
        string response;
        handler(request, response, icrDb);
        // if (request == "getId") {
        //     // 生成唯一ID
        //     response = to_string(id_counter++);
        // } else if (request.find("step=")==0) {
        //     std::cout << "更新时间步..." << std::endl;
        //     int step = atoi(request.substr(5).c_str());
        //     std::cout << "    step=" << step << "; !!!!!" << std::endl;
        // } else {
        //     // 存储文件
        //     ofstream file("server_storage.txt", ios::app);
        //     if (file.is_open()) {
        //         file << request << endl;
        //         file.close();
        //         response = "Stored successfully";
        //     } else {
        //         response = "File write failed";
        //     }
        // }
        // 发送响应
        write(new_socket, response.c_str(), response.length());
        close(new_socket);
    }
    return 0;
}

int processStepUpdate(const std::string& request, std::string& response, IcrDb& icrDb) {
    if (request.find("step=")==0) {
        icrDb.intMap["step"] = atoi(request.substr(5).c_str());
    }
    return 0;
}

int tcp_server_main() {
    // 设置UTF-8编码环境
    locale::global(locale("en_US.utf-8"));
    wcout.imbue(locale());

    int server_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    const int PORT = 8080;
    static int id_counter = 0;

    // 创建TCP socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 设置socket选项
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("setsockopt failed");
        exit(EXIT_FAILURE);
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // 绑定地址和端口
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 开始监听
    if (listen(server_fd, 3) < 0) {
        perror("listen failed");
        exit(EXIT_FAILURE);
    }
    cout << "Server listening on port " << PORT << "..." << endl;

    // 处理客户端连接
    while (true) {
        if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
            perror("accept failed");
            continue;
        }

        // 接收客户端数据
        char buffer[1024] = {0};
        int bytes_received = read(new_socket, buffer, 1024);
        if (bytes_received <= 0) {
            close(new_socket);
            continue;
        }

        string request(buffer, bytes_received);
        // 去除换行符和空格
        request.erase(request.find_last_not_of("\r\n") + 1);
        string response;
        if (request == "getId") {
            // 生成唯一ID
            response = to_string(id_counter++);
        } else if (request.find("step=")==0) {
            std::cout << "更新时间步..." << std::endl;
            int step = atoi(request.substr(5).c_str());
            std::cout << "    step=" << step << "; !!!!!" << std::endl;
        } else {
            // 存储文件
            ofstream file("server_storage.txt", ios::app);
            if (file.is_open()) {
                file << request << endl;
                file.close();
                response = "Stored successfully";
            } else {
                response = "File write failed";
            }
        }
        // 发送响应
        write(new_socket, response.c_str(), response.length());
        close(new_socket);
    }

    return 0;
}